29

Build Your Own Game—Tic Tac Toe

29

So how can we use this information to identify a winning row? And what if there

is no win but a draw?

This identifies a problem and the solution to this problem is an algorithm.

Here is the problem, written in somewhat mathematical terms:

• How can we define a function so that by executing this function on a set of any

three rows, the result represents a “Win”?

At this point we are clear that this requires the assignment of a unique number to

each cell.

See figure below.

1

2

3

4

5

6

7

8

9

FIGURE 2.26  Unique number for each cell.

Suppose we assign a unique integer to each cell 1,2,3…9.

We know that the following are winning combinations:

• Rows

• 1,2,3

• 4,5,6

• 7,8,9

• Columns

• 1,4,7

• 2,5,8

• 3,6,9

• Diagonals

• 1,5,9

• 3,5,7

One possible algorithm is to check the cells for this pattern. That would require a

longish if statement nest is like the one below:

If Cell 1 =​ “X”

If Cell2 =​ “X”

    If Cell3 =​ “X”

      XScore =​ Win

    End If